package org.tczs93.lunce.lucene;

import java.io.IOException;
import java.nio.file.Paths;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
 * @author ：tao.li
 * @description： lucene插入原始用法
 * @date ：Created in 2021/9/3 13:44
 */
public class LuceneIndexer {

    public boolean createIndex() throws IOException{
        String INDEX_DIR = "D:\\lucene";
        //加点测试的静态数据
        Integer ids[] = {1 , 2 , 3};
        String titles[] = {"JVM调优工具" , "JVM FULLGC频繁的案例1笔记" , "zookeeper实战笔记"};
        String tcontents[] = {
                "内容1内容啊哈哈哈",
                "内容2内容啊哈哈哈",
                "内容3内容啊哈哈哈"
        };

        //记录索引开始时间
        long startTime = System.currentTimeMillis();

        Analyzer analyzer = new SmartChineseAnalyzer();
        Directory directory = FSDirectory.open(Paths.get(INDEX_DIR));
        IndexWriterConfig config = new IndexWriterConfig(analyzer);

        IndexWriter indexWriter = new IndexWriter(directory, config);

        for(int i = 0; i < ids.length;i++){
            Document doc = new Document();
            //添加文档内容
            doc.add(new IntField("id", ids[i],Field.Store.YES));
            doc.add(new TextField("title", titles[i], Field.Store.YES));
            doc.add(new TextField("tcontent", tcontents[i], Field.Store.YES));
            indexWriter.addDocument(doc);
        }

        indexWriter.commit();
        System.out.println("共索引了"+indexWriter.numDocs()+"个文件");
        indexWriter.close();
        System.out.println("创建索引所用时间："+(System.currentTimeMillis()-startTime)+"毫秒");

        return true;
    }

}

